<template>
	<div class="wrapper">
		<!-- 商品图片 -->
		<div>
			<u-cell-group>
				<u-upload :header="{ accessToken: storage.getAccessToken() }" :action="action" width="200"
					:on-remove="removeFile"
					@on-uploaded="onUploaded" @on-success="fileSuccess" :file-list="baseInfoForm.goodsGalleryList" :max-count="5"
					:show-progress="false"></u-upload>
			</u-cell-group>
		</div>
		<!-- 基本信息 -->
		<u-cell-group>
			<u-cell-item class="step-title" title="基本信息" :arrow="false"></u-cell-item>
			<u-cell-item :arrow="false" title="商品名称">
				<u-input class="input" v-model='baseInfoForm.goodsName' :custom-style="inputStyle"></u-input>
			</u-cell-item>
			<u-cell-item :arrow="false" title="商品价格">
				<u-number-box :min="0" :positive-integer="false" v-model='baseInfoForm.price' :max='9999999'></u-number-box>元
			</u-cell-item>
			<u-cell-item title="商品卖点" :arrow="false">
				<u-input class="input" v-model='baseInfoForm.sellingPoint' type='textarea' :custom-style="inputStyle">
				</u-input>
			</u-cell-item>
			<u-cell-item title="商品品牌" :arrow="false">
				<u-input class="input" @click="showBrandList = true" disabled v-model='brandName'
					:custom-style="inputStyle"></u-input>
			</u-cell-item>
			<u-cell-item title="商品推荐" :arrow="false">
				<u-switch active-color="#333" v-model="baseInfoForm.recommend"></u-switch>
			</u-cell-item>
		</u-cell-group>


		<!-- 规格信息 -->
		<u-cell-group>
			<u-cell-item :arrow="false" title="规格信息"></u-cell-item>
			<div class="box">

				<div class="sku-item" v-for="(item, index) in skuInfo" :key="index">
					<div class='flex flex-a-c flex-j-sb'>
						<div class="h3" @click='handleEditGoodsName(item)'>
							{{ item.name }}
							<u-icon name='edit-pen'></u-icon>
						</div>
						<div @click='handleCloseSkuItem(index)'>
							删除
						</div>
					</div>
					<u-line></u-line>
					<div class='spec-item'>
						<u-tag class='sp-tag' :key="i" @close="handleCloseSkuValue(item, i)" closeable
							v-for="(spec, i) in item.spec_values" :text="spec.value" type="success">
						</u-tag>
					</div>
					<div class="add-spec" @click="handleClickAddSpec(item)">
						添加规格值
					</div>
				</div>
				<!-- 添加规格 -->
				<div class="add-sku" @click="handleClickAddSku">
					<u-icon color="#fff" style="margin-right: 20rpx;" name='plus' size="40"></u-icon> 添加新规格
				</div>
				<!-- sku详细 -->
				<div class='sku-detail' v-if='skuTableData.length'>
					<div class="h3">
						详细规格
					</div>
					<u-line></u-line>

					<u-table v-for="(sku, index) in skuTableData" :key='index'>
						<scroll-view scroll-x class='scroll'>
							<u-tr>
								<!-- 循环title -->
								<u-th v-for="(column, i) in skuColumn" :key='i'>{{ column.title }}</u-th>
							</u-tr>
							<div class='sku-table-item'>
								<u-tr>
									<u-th :key="skuIndex" v-if="sku[skuName.title]"
										v-for="(skuName, skuIndex) in skuColumn">
										{{ sku[skuName.title] }}
									</u-th>
									<u-th class="flex flex-a-c flex-j-c ">
										<u-image width="80rpx" height="80rpx"
											@click="preview(sku.images[0].url)" v-if="sku.images && sku.images.length"
											:src="sku.images[0].url">
										</u-image>
										<u-button size="mini" @click.stop="deleteSkuImg(sku,index)"
											v-if="sku.images && sku.images.length">删除</u-button>
										<u-upload v-else width="110rpx" height="100rpx"
											:header="{ accessToken: storage.getAccessToken() }" :action="action"
											@on-uploaded="onUploadedSku($event, sku, index)"
											@on-remove="removeImg($event, sku)" :file-list="sku.images"
											:show-upload-list='false' :max-count="1"
											></u-upload>
									</u-th>
								</u-tr>

								<!-- 商品编号 -->
								<div class='spec-div flex flex-a-c'>
									<div class='spec-title'>商品编号：</div>
									<u-input :custom-style="inputStyle" v-model="sku.sn" placeholder="商品编号"></u-input>
								</div>
								<div class='flex'>
									<!-- 商品重量 -->
									<div v-if="routerVal.goodsType != 'VIRTUAL_GOODS'" class='spec-div flex flex-a-c'>
										<div class='spec-title'>重量：</div>
										<u-number-box :min="0" :step="0.01" :positive-integer="false" :input-width="60" v-model="sku.weight"
											placeholder="商品重量">
										</u-number-box>
									</div>
									<!-- 商品库存 -->
									<div class='spec-div flex flex-a-c'>
										<div class='spec-title'>库存：</div>
										<u-number-box :min="0" :input-width="60" v-model="sku.quantity"
											placeholder="商品库存">
										</u-number-box>
									</div>
								</div>
								<div class='flex'>
									<div class='spec-div flex flex-a-c'>
										<div class='spec-title'>成本价：</div>
										<u-number-box :input-width="60" :step="0.01" :positive-integer="false" :min='0' :custom-style="inputStyle"
											v-model="sku.cost" placeholder="商品成本价格">
										</u-number-box>
									</div>
									<div class='spec-div flex flex-a-c'>
										<div class='spec-title'>价格：</div>
										<u-number-box :input-width="60" :step="0.01" :positive-integer="false" :min='0' :custom-style="inputStyle"
											v-model="sku.price" placeholder="商品价格">
										</u-number-box>
									</div>
								</div>
							</div>
						</scroll-view>
						<u-gap height="60" bg-color="#f7f7f7"></u-gap>
					</u-table>
				</div>


			</div>
		</u-cell-group>
		<!-- 规格显示 -->
		<u-modal confirm-color="#333" @confirm="handleAddSkuItem" show-cancel-button title="设置规格"
			v-model="showSkuModal">
			<div class='slot flex flex-a-c'>
				<div class='sku-name'>规格名称</div>
				<u-input v-model="skuModalName" placeholder="请输入规格名称"></u-input>
			</div>
		</u-modal>


		<!-- 商品交易信息 -->
		<u-cell-group>
			<u-cell-item class="step-title" title="交易信息" :arrow="false"></u-cell-item>
			<u-cell-item title="计量单位" @click="getGoodsUnit" :value="baseInfoForm.goodsUnit"></u-cell-item>
			<u-cell-item title="销售模式" :arrow="false">
				<u-radio-group v-if="baseInfoForm.goodsType != 'VIRTUAL_GOODS'" v-model="baseInfoForm.salesModel">
					<u-radio active-color="#333" v-for="(item, index) in goodsTypeRadioList" :key="index"
						:name="item.value">
						{{ item.name }}
					</u-radio>
				</u-radio-group>
				<u-radio-group v-else v-model="baseInfoForm.salesModel">
					<u-radio active-color="#333" name="RETAIL">
						虚拟型
					</u-radio>
				</u-radio-group>
			</u-cell-item>
			
			<!-- 批发 -->
			<template v-if="baseInfoForm.salesModel === 'WHOLESALE'">
				<u-cell-item class="step-title" title="批发设置" :arrow="false"></u-cell-item>
				<view>
					<u-table bg-color="#eee" :th-style="thStyle">
						<u-tr>
							<u-th>购买数量</u-th>
							<u-th>单价</u-th>
							<u-th>操作</u-th>
						</u-tr>
						<u-tr v-for="(item,index) in wholesaleList" :key="index">
							<u-th>
								<u-number-box v-model="item.num"
								  :input-width="60" 
								  :min="(wholesaleList.length -1 ) === 0 ? 1 :(wholesaleList.length - 1 ) > index && index != 0 ? wholesaleList[index - 1].num + 1 : 1"
								  :max="(wholesaleList.length - 1 === 0) ? 9999999 :(wholesaleList.length -1 ) > index ? wholesaleList[index + 1].num - 1 : 9999999"
								  :custom-style="inputStyle"
								 placeholder="购买数量">
								</u-number-box>
							</u-th>
							<u-th>
								<u-number-box 
								v-model="item.price" 
								:input-width="60" 
								:step="0.01" 
								:positive-integer="false" 
								:custom-style="inputStyle"
								:min="(wholesaleList.length - 1  === 0) ? 0.01 :(wholesaleList.length - 1 ) > index ? wholesaleList[index + 1].price + 0.01 : 0.01"
								:max="(wholesaleList.length - 1 === 0) ? 999999999 :(wholesaleList.length -1 ) >= index && index != 0 ? wholesaleList[index - 1].price - 0.01 : 999999999"
								 placeholder="单价">
								</u-number-box>
							</u-th>
							<u-th>
								<u-button @click="delWholesale(index)" type="error" size="mini">删除</u-button>
							</u-th>
						</u-tr>
						<u-tr v-if="wholesaleList.length < 3">
							<u-th>
								<u-button @click="handleAddWholesaleData">+ 添加价格区间</u-button>
							</u-th>
						</u-tr>
						<u-tr>
							<u-th>销售规则</u-th>
						</u-tr>
						<u-tr v-for="(item,index) in wholesaleList" :key="index+'rules'">
							<u-th>
							{{index + 1}}.当商品购买数量 ≥{{item.num}} 时，售价为 ￥{{item.price}}
							</u-th>
						</u-tr>
					</u-table>
				</view>
			</template>
		</u-cell-group>

		<u-cell-group>
			<u-cell-item class="step-title" title="商品详情" :arrow="false"></u-cell-item>
			<u-cell-item title="店内分类" :arrow="false">
				<tree class='tree' :defaultCheckedKeys="storeCategoryPath" @cnecked="treeChecked"
					:treeData="shopCategory" :replaceFields="{ children: 'children', key: 'id', name: 'title' }" />
			</u-cell-item>

			<!-- <u-cell-item class="step-title" @click='handleClickToGoodsIntro' title="商品介绍" :arrow="false">
				<div class='goods-intro'>
					<div v-html="baseInfoForm.mobileIntro">

					</div>
				</div>
			</u-cell-item> -->

		</u-cell-group>
		<u-cell-group>
			<u-cell-item class="step-title" title="物流信息" :arrow="false"></u-cell-item>
			<u-cell-item title="物流模版" :arrow="false">
				<u-input class="input" @click="showLogTemplate = true" disabled v-model='logTemplateName'
					:custom-style="inputStyle"></u-input>
			</u-cell-item>
		</u-cell-group>

		<!-- 循环的商品参数 -->
		<u-cell-group v-for="(paramsGroup, groupIndex) in goodsParams" :key='groupIndex'>
			<u-cell-item class="step-title" :title="paramsGroup.groupName" :arrow="false"></u-cell-item>
			<u-cell-item :key="index" class="goods-params-item" :arrow="false"
				v-for="(item, index) in paramsGroup.params" :title="item.paramName">
				<div class='flex flex-j-fe'>
					<u-input style="width: 300rpx;" @click="handleClickGoodsParams(item, paramsGroup)"
						v-model="item.paramValue" disabled :custom-style="inputStyle"></u-input>
				</div>
			</u-cell-item>
		</u-cell-group>
		<div @click="save" class='submit fixed'>
			保存/修改规格
		</div>

		<!-- 商品参数 -->
		<u-select @confirm="confirmGoodsParams" v-model="showGoodsParams" :list="goodsParamsList"></u-select>
		<!-- 物流模版 -->
		<u-select @confirm="confirmLogTemp" v-model="showLogTemplate" :list="logisticsTemplate"></u-select>
		<!-- 商品品牌 -->
		<u-select @confirm="confirmBrand" v-model="showBrandList" :list="brandList"></u-select>
	</div>
</template>

<script>
import storage from "@/utils/storage.js";
import {
	upload
} from "@/api/common.js";
import uuid from "@/utils/uuid.modified.js";
import * as API_Goods from "@/api/goods";
import tree from '@/components/xy-tree/xy-tree.vue'

// #ifdef MP-WEIXIN
import cuEditor from '@/components/cu-editor/cu-editor'
// #endif

export default {
	components: {
		tree,
		// #ifdef MP-WEIXIN
		cuEditor
		// #endif
	},

	data() {
		return {
			thStyle:{
				"width":"47vw",
			},
			storage,
			inputStyle: {
				background: "#f7f7f7",
				"padding-left": "20rpx",
				"border-radius": "10rpx",
			},
			action: upload, //图片上传数据
			goodsParams: "", //商品参数
			categorys: "", //商品分类显示内容
			goodsData: {}, //商品详情
			brandList: [], //品牌列表
			brandName: "", //显示品牌的名称
			showBrandList: false, // 是否显示品牌
			logisticsTemplate: [], // 物流模版
			showLogTemplate: false, // 是否显示物流模版
			logTemplateName: '', // 物流模版昵称
			showGoodsParams: false, // 是否显示商品参数
			selectedParams: "", //选择的商品参数
			goodsParamsList: [], //商品参数列表
			shopCategory: [], //店铺分类列表
			// 商品类型
			goodsTypeRadioList: [{
				name: '零售型',
				value: "RETAIL"
			},
			{
				name: '批发型',
				value: "WHOLESALE"
			},
			],
			// 商品单位查询params
			unitParams: {
				pageNumber: 1,
				pageSize: 10
			},
			baseInfoForm: {
				salesModel: "RETAIL",
				/** 商品相册列表 */
				goodsGalleryFiles: [],
				/** 是否立即发布 true 立即发布 false 放入仓库 */
				release: true,
				/** 是否为推荐商品 */
				recommend: true,
				/** 店铺分类 */
				storeCategoryPath: "",
				brandId: 0,
				/** 计量单位 **/
				goodsUnit: "",
				/** 商品类型 **/
				goodsType: "",
				/** 分类路径 **/
				categoryPath: [],
				/** 商品卖点 **/
				sellingPoint: "",
				/** 商品详情 **/
				intro: "",
				mobileIntro: "",
				updateSku: true,
				/** 是否重新生成sku */
				regeneratorSkuFlag: false,
				/** 物流模板id **/
				templateId: "",
				/** 参数组*/
				goodsParamsDTOList: [],
				/** 商品分类中文名 */
				categoryName: [],
				price: 1
			}, // 商品信息
			goodsTypeCurrent: 0, //商品类型索引
			categoryId: "", //商品分类id

			tempId: "", //模版id
			goodsId: '', // 商品编辑id
			storeCategoryPath: [], //店铺store的分类集合


			showSkuModal: false, //显示规格内容
			skuModalName: '', //弹出框保存的规格信息
			skuInfo: [], // sku详情
			/** sku表格数据 */
			skuTableData: [],
			wholesaleList:[{
				num:1,
				price:1
			}],

			skuData: '',
			skuColumn: [{
				title: "图片",
				slot: "images",
			}],
			routerVal: "",
			selectSku: "",
			selectAddSkuType: '', //选择添加sku type
			initSkuList: [],
			initSkuTableData: [],
			// 手动验证规则
			rulesList: [{
				key: "goodsName",
				errorMessage: '商品名称'
			}, {
				key: "sellingPoint",
				errorMessage: '商品卖点'
			}, {
				key: "goodsUnit",
				errorMessage: '计量单位'
			}, {
				key: "templateId",
				errorMessage: '物流模板'
			},],
			ignoreColumn: [
				// 添加规格时需要忽略的参数
				"_index",
				"_rowKey",
				"sn",
				"cost",
				"price",
				"weight",
				"quantity",
				"specId",
				"specValueId",
			],
			goodsGalleryFilesArr:[],
			specificationImg:[]
		};
	},
	props: {
		stepData: {
			type: null
		}
	},

	watch: {
		stepData: {
			handler(val) {
				if (val.category) {
					val.category.forEach(item => {
						this.baseInfoForm.categoryPath.push(item.value)
						this.baseInfoForm.categoryName.push(item.label)
					})
				}

				// this.baseInfoForm.category = val.goodsType
				this.baseInfoForm.goodsType = val.goodsType
				this.baseInfoForm.goodsUnit = val.goodsUnit?val.goodsUnit:""
				this.tempId = val.tempId
				this.goodsId = val.id

				this.categoryId = val.category ? val.category[2].value : '';

			},
			deep: true,
			immediate: true
		},
		// 监听模版id
		tempId(val) {
			if (val) {
				console.log("tempId", val)
				this.GET_GoodData('', val)
			}
		},
		// 商品编辑id
		goodsId(val) {
			if (val) {
				this.GET_GoodData(val, '')
			}
		}
	},
	mounted() {
		if (this.tempId || this.goodsId) {
			this.GET_GoodData(this.goodsId, this.tempId)
		} else {
			this.init()
		}
	},

	methods: {
		delWholesale(index){
			this.wholesaleList = this.wholesaleList.filter((item,i)=> i != index)
		},
		handleAddWholesaleData(){
			if(this.wholesaleList.length === 3){
				uni.showToast({
					title:"最多添加3个价格区间！",
					icon:"none"
				})
				return
			}
			if(this.wholesaleList.length){
				this.wholesaleList=[
					...this.wholesaleList,
					{
						num:this.wholesaleList[this.wholesaleList.length-1].num + 1,
						price:this.wholesaleList[this.wholesaleList.length-1].price - 0.01
					}
				]
			}else{
				this.wholesaleList=[
					{
						num:1,
						price:1
					}
				]
			}
		},
		deleteSkuImg(sku,index){
			this.$set(this.skuTableData, index, {
				...this.skuTableData[index],
				images : []
			})
		},
		handleClickToGoodsIntro() {
			uni.navigateTo({
				url: '/pages/goods/step/goodsIntro'
			})
		},
		/**
		 * 点击图片放大或保存
		 */
		preview(urls, index) {
			uni.previewImage({
				current: index,
				urls: [urls],
				longPressActions: {
					itemList: ["保存图片"],
					success: function (data) { },
					fail: function (err) { },
				},
			});
		},
		//移除图片
		removeImg(index, sku) {
			this.$set(this.skuTableData, index, {
				...this.skuTableData[index],
				images : []
			})
		},

		// 图片上传
		onUploadedSku(lists, sku, index) {
			// console.log("lists",lists,index);
			this.$set(this.skuTableData, index, {
				...this.skuTableData[index],
				images:[
					{
						'url': lists[0].response.result
					}
				]
			})
			this.$set(this.initSkuTableData, index, {
				...this.initSkuTableData[index],
				images:[
					{
						'url': lists[0].response.result
					}
				]
			})
		},
		required() {
			if (this.skuModalName == '') {
				uni.showToast({
					title: '请填写内容',
					icon: 'none'
				})
				return false
			}
			return true
		},
		// 添加规格项
		handleClickAddSpec(val) {
			this.showSkuModal = true
			this.skuModalName = ''
			this.selectAddSkuType = 'addSpec'
			this.selectSku = val
		},
		// 点击添加新规格
		handleClickAddSku() {
			if (this.skuInfo.length >= 5) {
				this.$Message.error("规格项不能大于5个！");
				return;
			} else {

				this.selectAddSkuType = 'addSku'
				this.handleAddSkuItem()
			}
		},
		// 移除当前规格值
		handleCloseSkuValue(item, index) {
			item.spec_values.splice(index, 1);
			this.renderTableData();
		},
		// 移除当前大规格项
		handleCloseSkuItem(index) {
			this.skuInfo.splice(index)
			this.renderTableData();
		},
		// 修改商品规格名
		handleEditGoodsName(val) {
			this.showSkuModal = true
			this.skuModalName = ''
			this.selectSku = val
			this.selectAddSkuType = 'editSku'
		},
		/** 添加规格项 */
		handleAddSkuItem() {
			// 如果是添加规格项

			if (this.selectAddSkuType == 'addSpec') {
				if (this.selectSku.spec_values >= 10) {
					uni.showLoading({
						title: '规格值不能大于10个！'
					})
				} else {
					if (!this.required()) return
					// 写入填写的规格值
					this.$set(this.selectSku.spec_values, this.selectSku.spec_values.length, {
						name: this.selectSku.name,
						value: this.skuModalName,
						_id: new Date().getTime()
					});
					console.log("热乎的",this.selectSku);
				}
				// 添加sku
			} else if (this.selectAddSkuType == 'addSku') {
				// 写入对象，下标，具体对象

				this.$set(this.skuInfo, this.skuInfo.length, {
					spec_values: [{
						name: '规格项',
						value: "规格项值" + this.skuInfo.length,
						_id: new Date().getTime() + Math.random(0.1)

					}],
					name: "规格名" + parseInt(this.skuInfo.length),
					_id: new Date().getTime()
				});
			}
			// 编辑sku名字
			else {
				this.selectSku.name = this.skuModalName

			}
			this.renderTableData();
		},
		// 初始化sku信息
		initSku(skuList) {
			let skuWay = []
			let skusInfo = []
			skuList.map((e, skuListIndex) => {
				// 循环规格信息
				let sku = {
					id: e.id,
					_id: new Date().getTime() + skuListIndex,
					sn: e.sn,
					price: e.price ? e.price : 1,
					cost: e.cost ? e.cost : 1,
					quantity: e.quantity ? parseInt(e.quantity) : 1,
					weight: e.weight ? e.weight : 1,
				};

				// 初始化规格spec
				e.specList.forEach((u, _index) => {
					// 如果规格名是images将 sku的image进行复值
					if (u.specName === "images") {
						sku.images = u.specImage;

					} else {
						// 给最外层设置一个 规格名的key值
						sku[u.specName] = u.specValue;

						// 如果当前sku里面的name 没有值并且 没有添加规格时需要忽略的参数的时候像当前sku里面push内容
						if (
							!skusInfo.some((s) => s.name === u.specName) &&
							!this.ignoreColumn.includes(u.specName)
						) {
							skusInfo.push({
								name: u.specName,
								spec_id: u.specNameId,
								_id: new Date().getTime(),
								spec_values: [{
									_id: new Date().getTime(),
									name: u.specName,
									value: u.specValue || "",

								},],
							});
						} else {
							// 如果有sku name值进行处理
							skusInfo = skusInfo.map((sk, sk_i) => {
								if (
									!sk.spec_values.some((s) => s.value === u
										.specValue) &&
									sk.name === u.specName
								) {
									sk.spec_values.push({
										_id: new Date().getTime(),
										name: u.specNames,
										value: u.specValue || "",

									});
								}
								if (!sk.spec_id && u.specName === "specId") {
									sk.spec_id = u.specValue;
								}
								return sk;
							});
						}
					}

				});
				skuWay.push(sku)
			})
			console.log("skuWay",skuWay);
			return {
				sku: skuWay,
				skuInfo: skusInfo
			}
		},
		// 初始化规格title , 表格等内容
		initSkuData(skuList) {
			if (!skuList.length) return false
			const {
				sku,
				skuInfo
			} = this.initSku(skuList);
			console.log("sku",sku, "skuInfo",skuInfo)
			this.skuInfo = skuInfo
			skuInfo.forEach(sku => {
				this.skuColumn.unshift({
					title: sku.name,
					key: sku.name,
				});
			})
			this.skuTableData = sku
		},

		// 渲染表格
		renderTableData() {
			this.skuColumn = []
			this.initSkuTableData = this.skuTableData
			this.skuTableData = []
			console.log("skuInfo",this.skuInfo);
			this.skuInfo.forEach(sku => {
				this.skuColumn=[
					...this.skuColumn,
					{
						title: sku.name,
						key: sku.name,
					}
				]
			})
			
			this.skuColumn.push({
				title: "图片",
				slot: "images",
			});
			let cloneTemp = JSON.parse(JSON.stringify(this.skuInfo));
			//判定 是否存在规格分组
			if (cloneTemp[0]) {
				//存放最终结果
				let result = [];
				/**
				 * 循环选中的 sku 数据
				 * */
				cloneTemp[0].spec_values.forEach((specItem) => {

					let obj = {
						[cloneTemp[0].name]: specItem.value,
						images: [],
						_name: cloneTemp[0].name,
						...specItem
					}

					result.push(obj);
				});
				/**
				 * 此时已经删除掉了 数组中第一个内容
				 * 并已将数组中的规格赋值给了 result 
				 * cloneTemp 则是剩余的规格项
				 * 
				 * */
				cloneTemp.splice(0, 1);
				// 继续循环出规格项
				console.log("result",result);
				result = this.specIterator(result, cloneTemp);

				this.skuTableData = result


				this.initSkuTableData.forEach(sku => {
					this.skuTableData.forEach((item, index) => {
						// 多个规格项 判断每个id数组通过赋值
						if (sku._id && sku._id.length && this.scalarArrayEquals(item._id, sku._id)) {
							this.skuTableData[index] = {
								...item,
								...sku
							}

						} else if (item.value == sku[item._name] || item._id == sku._id) {
							// 	// 单个规格项如果id重复 赋值
							this.skuTableData[index] = {
								...item,
								...sku
							}
							// }
						}
					})
				})

			}

		},
		// 判断相同数组的值
		scalarArrayEquals(array1, array2) {
			return array1.length ===
				array2.length &&
				array1.every(function (v, i) {
					return v === array2[i]
				})
		},


		/**
		 * 迭代属性，形成表格
		 * result 渲染的数据
		 * array spec数据
		 */
		specIterator(result, cloneTemp) {

			if (cloneTemp.length > 0) {
				let table = [];
				result.forEach((resItem) => {
					cloneTemp[0].spec_values.forEach((valItem, i) => {
						let obj = JSON.parse(JSON.stringify(resItem));

						obj[cloneTemp[0].name] = valItem.value;
						obj._name = obj[cloneTemp[0].name]
						if (obj._id) {
							obj._id = `${obj._id},${obj._id + i}`.split(',')
						}
						console.log(obj)
						// 将规格排序出来
						table.push(obj);
					});
				});

				result = [];
				table.forEach((t) => {

					result.push(t);
				});
				cloneTemp.splice(0, 1);
			} else {
				return result;
			}
			return this.specIterator(result, cloneTemp);
		},




		// 初始化内容
		init() {
			this.GET_GoodsBrandList() // 商品品牌
			this.GET_ShipTemplate(); // 物流模版
			this.GET_ShopGoodsLabel(); // 获取当前店铺分类
			this.GET_GoodsParams(); // 商品参数

		},

		// 添加商品
		async save() {
			let submit = JSON.parse(JSON.stringify(this.baseInfoForm));
		
			if(submit.categoryPath instanceof Array){
				submit.categoryPath = submit.categoryPath.join(",")
			}
			if(submit.storeCategoryPath  instanceof Array){
				submit.storeCategoryPath = submit.storeCategoryPath.join(",")
			}
			
			if(this.goodsData.images){
				submit.goodsGalleryFiles = [
					...submit.goodsGalleryFiles,
					...this.goodsData.images
				]
			}else{
				uni.showToast({
					title: '请上传商品图片',
					icon: 'none'
				})
				return;
			}
			if (submit.goodsGalleryFiles.length > 0) {
				submit.goodsGalleryList = submit.goodsGalleryFiles
			}
			console.log(submit, this.skuTableData)
			// 校验图片是否上传
			if (
				submit.goodsGalleryList &&
				submit.goodsGalleryList.length <= 0
			) {
				uni.showToast({
					title: '请上传商品图片',
					icon: 'none'
				})
				return;
			}
			
			if (!this.skuTableData.length) {
				uni.showToast({
					title: `请添加规格`,
					icon: 'none'
				})
				return;
			}
			let require = ['cost', 'price', 'quantity']
			submit.skuList = this.skuTableData.map((sku, index) => {
				// 必填项如果没有填写则设置为0
				require.forEach(item => {
					sku[item] == null || sku[item] == undefined ? sku[item] = 1 : ''
				})
				delete sku._index;
				delete sku._rowKey;
				delete sku.specNameId;
				delete sku.specValueId;
				delete sku._id;
				delete sku.name;
				delete sku.value;
				delete sku._name
				return sku;
			})
			let enableSubmit = true
			// 手动验证规则

			this.rulesList.forEach(rule => {
				if (!submit[rule.key]) {
					uni.showToast({
						title: `请输入${rule.errorMessage}`,
						icon: 'none'
					})
					enableSubmit = false
					return
				}
			})
			if (!this.baseInfoForm.goodsUnit) {
				uni.showToast({
					title: `请输入计量单位`,
					icon: 'none'
				})
			}
			//判断
			if(submit.price.toString().indexOf(".")!= -1){
				if(submit.price.toString().split(".")[1].length > 2){
					uni.showToast({
						title:"商品价格小数位不能大于2",
						icon:"none"
					})
					return
				}
			}
			for(let i = 0; i < submit.skuList.length; i++){
				if(submit.skuList[i].price.toString().indexOf(".") != -1){
					if(submit.skuList[i].price.toString().split(".")[1].length > 2){
						uni.showToast({
							title:`[规格]${submit.skuList[i][this.skuColumn[0].key]} 价格小数位不能大于2`,
							icon:"none"
						})
						return
					}
				}
				if(submit.skuList[i].cost.toString().indexOf(".") != -1){
					if(submit.skuList[i].cost.toString().split(".")[1].length > 2){
						uni.showToast({
							title:`[规格]${submit.skuList[i][this.skuColumn[0].key]} 成本价小数位不能大于2`,
							icon:"none"
						})
						return
					}
				}
			}

			//循环遍历重量规格项是否添加
			submit.skuList.forEach(item=>{
				if(item.weight === undefined){
					item.weight = 1
				}
			})
			if(submit.salesModel === "WHOLESALE"){
				for(let i =0;i<this.wholesaleList.length;i++){
					if(this.wholesaleList[i].price.toString().indexOf(".") != -1){
						if(this.wholesaleList[i].price.toString().split(".")[1].length > 2){
							uni.showToast({
								title:`[批发金额]规则${i + 1} 价格小数位不能大于2`,
								icon:"none"
							})
							return
						}
					}
				}
				submit.wholesaleList = this.wholesaleList
			}
			if (enableSubmit) {
				uni.showLoading({
					title: '加载中'
				})
				try {
					let res
					if (this.goodsId) {
						console.log("upLoad",submit);
						// goodsGalleryFilesArr
						submit.goodsGalleryFiles = this.goodsGalleryFilesArr
						console.log("submit", submit)
						// return
						res = await API_Goods.editGoods(this.goodsId, submit)
					} else {
						submit.goodsGalleryFiles = this.goodsGalleryFilesArr
						console.log(submit, this.skuTableData)
						// return
						if(submit.skuList){
							submit.skuList.forEach(item=>{
								if(!item.id){
									delete item.id
								}
							})
						}
						res = await API_Goods.createGoods(submit)
					}
					if (res.data.success) {
						uni.showToast({
							title: '操作成功!',
							icon: 'none'
						})
						uni.navigateBack()
					}
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			}


			// 
		},

		// 获取商品信息 编辑/商品模版
		async GET_GoodData(goodsId, draftId) {
			uni.showLoading({
				title: '加载中'
			})
			let response
			if (draftId) {
				response = await API_Goods.getDraftGoodsDetail(draftId);
			} else {
				response = await API_Goods.getGoods(goodsId);
				this.goodsId = response.data.result.id;
			}
			uni.hideLoading()
			// 初始化数据内容
			const data = response.data.result
			console.log('data',data);
			this.baseInfoForm = {
				...this.baseInfoForm,
				...data
			};
			if(data.wholesaleList || (Array.isArray(data.wholesaleList) ? data.wholesaleList.length : true)){
				this.wholesaleList = [
					{
						num:1,
						price:1
					}
				]
			}else{
				this.wholesaleList = data.wholesaleList
			}
			this.storeCategoryPath = data.storeCategoryPath.split(",")
			//  初始化商品分类
			this.categoryId = data.categoryPath.split(",")[2];
			// 初始化商品图片
			this.baseInfoForm.goodsGalleryList = data.goodsGalleryList.map(img=>{
				return {
					url:img
				}
			})
			this.baseInfoForm.goodsGalleryFiles = data.goodsGalleryList
			this.goodsGalleryFilesArr = [...this.baseInfoForm.goodsGalleryList]
			this.initSkuData(response.data.result.skuList);
			/** 查询品牌列表 */
			this.GET_GoodsBrandList(response.data.result.brandId);
			this.GET_ShipTemplate(response.data.result.templateId)
			this.GET_ShopGoodsLabel(); // 获取当前店铺分类
			/** 查询商品参数 */
			this.GET_GoodsParams();
		},
		/**
		 * 点击商品类型 查询当前要绑定的商品集合
		 */
		handleClickGoodsParams(item, data) {
			this.selectedParams = item
			this.goodsParamsList = item.options ? item.options.split(',').map(item => {
				return {
					value: item,
					label: item
				}
			}) : [],
				this.showGoodsParams = true
		},
		// 点击确认商品参数
		confirmGoodsParams(val) {
			this.goodsParams.forEach(item => {
				if (item.params.length) {
					item.params.forEach(param => {
						if (param.id == this.selectedParams.id) {
							param.paramValue = val[0].value
							console.log(param)
						}
					})
				}
			})
			console.log(this.selectedParams, val)

		},
		// 店铺分类点击回调数据
		treeChecked(val, checked, checkedKeys) {
			this.baseInfoForm.storeCategoryPath = checkedKeys
		},

		// 商品计量单位
		getGoodsUnit() {
			uni.navigateTo({
				url: '/pages/goods/step/goodsUnit'
			})
		},

		// 图片上传
		onUploaded(lists) {
			let images = [];
			lists.forEach((item) => {
				console.log(item);
				if(item.response){
					images.push(item.response?.result);
				}
			});
			console.log("lists",lists);
			let fileUpload = lists[lists.length - 1].file
			let obj = {
				name:fileUpload.name,
				percentage:lists[lists.length - 1].percentage,
				showProgress:lists[lists.length - 1].error,
				size:fileUpload.size,
				status:"finished",
				url:lists[lists.length - 1].response.result,
				response:lists[lists.length - 1].response,
				uid:uuid.v1()
			}
			if(lists[lists.length - 1].response.code === 200){
				this.goodsGalleryFilesArr = [
					...this.goodsGalleryFilesArr,
					obj
				]
			}
			console.log("goodsGalleryFilesArr",this.goodsGalleryFilesArr);
			// return
			this.goodsData.images = images;
			console.log(this.baseInfoForm.goodsGalleryList);
		},
		removeFile(index, lists, name){
			console.log(index, lists, name);
		},
		fileSuccess(data, _, _1, name){
			console.log("name",name);
		},
		// 选择/确认品牌
		confirmBrand(val) {
			console.log(val)
			this.baseInfoForm.brandId = val[0].value
			this.brandName = val[0].label
		},
		// 选择/确认物流模版
		confirmLogTemp(val) {
			this.baseInfoForm.templateId = val[0].value
			this.logTemplateName = val[0].label
		},
		/** 
		 * 查询商品品牌列表
		 * */
		GET_GoodsBrandList(id) {
			API_Goods.getCategoryBrandListDataSeller(this.categoryId).then(
				(response) => {
					console.log("GoodsBrandList", response);
					this.brandList = response.data.map(item => {
						if (item.id == id) {
							this.brandName = item.name
							console.log("brandName", this.brandName);
						}
						return {
							label: item.name,
							value: item.id
						}
					});
					console.log("brandList", this.brandList);
				}
			);
		},
		// 获取商品模版
		GET_ShipTemplate(id) {
			API_Goods.getShipTemplate().then((res) => {
				if (res.data.success) {
					this.logisticsTemplate = res.data.result.map(item => {
						if (item.id == id) this.logTemplateName = item.name
						return {
							label: item.name,
							value: item.id
						}
					});;
				}
			});
		},
		// 获取当前店铺分类
		GET_ShopGoodsLabel() {
			API_Goods.getShopGoodsLabelListSeller().then((res) => {
				if (res.data.success) {
					let shopCategories = !this.baseInfoForm.storeCategoryPath ? [] :
						this.baseInfoForm.storeCategoryPath.split(",");



					this.shopCategory = res.data.result.map((i) => {
						i.title = i.labelName;
						i.expand = false;
						i.checked = shopCategories.some((o) => o === i.id);
						i.children = i.children.map((j) => {
							j.title = j.labelName;
							j.expand = false;
							j.checked = shopCategories.some((o) => o === j.id);
							return j;
						});
						return i;
					});

					console.log('shopCategory', this.shopCategory)
				}
			});
		},

		/** 根据当前分类id查询商品应包含的参数 */
		GET_GoodsParams() {
			API_Goods.getCategoryParamsListDataSeller(this.categoryId).then(
				(response) => {
					if (!response || response.data.length <= 0) {
						return;
					}
					this.goodsParams = response.data;

					if (this.baseInfoForm.goodsParamsDTOList) {
						// 已选值集合
						const paramsArr = [];
						this.baseInfoForm.goodsParamsDTOList.forEach((group) => {
							group.goodsParamsItemDTOList.forEach((param) => {
								param.groupId = group.groupId;
								paramsArr.push(param);
							});
						});
						// 循环参数分组
						this.goodsParams.forEach((parmsGroup) => {
							parmsGroup.params.forEach((param) => {
								paramsArr.forEach((arr) => {
									if (param.paramName == arr.paramName) {
										param.paramValue = arr.paramValue;
									}
								});
							});
						});
					} else {
						this.baseInfoForm.goodsParamsDTOList = [];
					}
				}
			);
		},
	},
};
</script>
<!-- #ifdef MP-WEIXIN -->
<style>
page {
	background: rgb(247, 247, 247) !important;

}
</style>
<!-- #endif  -->
<!-- #ifndef MP-WEIXIN -->
<style scoped>
page {
	background: rgb(247, 247, 247) !important;
	padding: 16rpx;
}
</style>
<!-- #endif -->
<style lang="scss" scoped>
@import "./style.scss";
/deep/ .u-numberbox{
	justify-content: center;
}
 .u-cell-item-box {
	margin: 0 16rpx;
}

.fixed {
	border-radius: 0;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 9;
	width: 100%;
}

.wrapper {
	padding: 0 0 32rpx 0;
	background: rgb(247, 247, 247);
}

.u-cell-box {
	width: 96% !important;
	margin: 30rpx 2%;
	overflow: hidden;
	border-radius: 20rpx;
}

.u-cell-box:nth-of-type(1) {
	margin-top: 0;
}

.tabs {
	margin: 20rpx 0;
}

/deep/ .u-cell__value {
	margin-left: 50rpx;
}

.tree {
	text-align: left;
	margin-left: 20rpx;
}

.sp-tag {
	margin: 10rpx;

}




.sku-table-item {
	margin-bottom: 40rpx;
}

.add-spec {
	margin: 20rpx 0;
	background: #ededed;
	width: 200rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	border-radius: 10rpx;
}

.spec-div {
	padding: 0 8rpx;
	margin: 20rpx 0;

	>.spec-title {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
	}
}

.sku-item,
.sku-detail {
	border-radius: 20rpx;
	background: #fff;
	margin-bottom: 48rpx;
}

.u-table {
	width: 100%;
	overflow: auto;
	margin-bottom: 20rpx;
}

.box {
	padding: 48rpx 16rpx;
}

.u-th {
	width: 20%;
	height: 120rpx;
	overflow-x: auto;
	align-items: center;
}

/* #ifdef MP-WEIXIN */
/deep/ u-th > view {
	height: 130rpx;
	align-items: center;
}
/* #endif */
.h3 {
	margin: 20rpx 0;
}

.spec-item {
	margin-top: 20rpx;
}

.slot {
	padding: 32rpx;

	>.sku-name {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
	}
}

.add-sku {
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #333;
	color: #fff;
	width: 100%;
	margin: 40rpx auto;
	border-radius: 10rpx;

}

.goods-intro {
	height: 600rpx;
	overflow-y: auto;
}
</style>
